<template>
  <div class="chart-content">
    <div class="table-title">
      <span>{{echartTitle}}</span>
      <div class="right-content">
        <slot name="right"></slot>
      </div>
    </div>
    <div
      class="chart"
      :id="id"
      :option="option"
    ></div>
    <div
      v-if="noData"
      class="no-data"
    >{{noDataTip}}</div>
  </div>
</template>
<script>
require('echarts/theme/macarons') // echarts theme
import { mapState } from 'vuex'
import DEFAULT_OPTION from './defaultOption'
export default {
  props: {
    echartTitle: {
      type: String,
      default: ''
    },
    option: {
      type: Object,
      default: () => {
        return {}
      }
    },
    id: {
      type: String,
      default: '',
      required: true
    },
    canClick: {
      type: Boolean,
      default: false
    },
    noDataTip: {
      type: String,
      default: "暂无数据"
    }
  },
  data() {
    return {
      chart: null,
      noData: true
    }
  },
  computed: {
    ...mapState({
      sidebar: (state) => state.app.sidebar
    }),
    sidebarTrigger() {
      return this.sidebar.opened
    }
  },
  watch: {
    option: {
      handler: function (n, o) {
        if (!n) {
          return
        }
        if (!this.chart) {
          this.$nextTick(() => {
            const chart = this.$echarts.init(document.getElementById(this.id))
            const defaultOption = JSON.parse(JSON.stringify(DEFAULT_OPTION))
            this.utils.deepMerge(defaultOption, n)
            this.chart = chart
            if (defaultOption?.xAxis && defaultOption?.xAxis[0].data) {
              this.getZoomConfigData(defaultOption, defaultOption.xAxis[0].data)
            }

            chart.setOption(defaultOption)
            this.setEvent()
            if (!defaultOption.series.length) {
              this.noData = true
            } else {
              this.noData = false
            }
          })
        } else {
          this.$nextTick(() => {
            this.chart.clear()
            const defaultOption = JSON.parse(JSON.stringify(DEFAULT_OPTION))
            this.utils.deepMerge(defaultOption, n)
            if (defaultOption?.xAxis && defaultOption?.xAxis[0].data) {
              this.getZoomConfigData(defaultOption, defaultOption.xAxis[0].data)
            }
            this.chart.setOption(defaultOption)
            this.setEvent()
            if (!defaultOption.series.length) {
              this.noData = true
            } else {
              this.noData = false
            }
          })
        }
      },
      deep: true,
      immediate: true
    },
    sidebarTrigger() {
      this.handleResize()
    }
  },
  methods: {
    handleResize() {
      setTimeout(() => {
        this.chart?.resize()
      }, 100)
    },
    getZoomConfigData(defaultOption, list) {
      if (defaultOption.dataZoom) {
        return
      }
      let barNum = list.length
      let longest = list.reduce((prev, next) => {
        return prev.length > next.length ? prev.length : next.length
      }, '')
      // 容器宽度
      let contentWidth = 0
      const chartContent = document.getElementById(this.id)
      if (chartContent) {
        contentWidth = chartContent.offsetWidth - 30
      }

      const minLen = defaultOption.legend.data.length * 20
      let perBarWidth = longest * 12
      if (perBarWidth < minLen) {
        perBarWidth = minLen
      }

      const maxBarNum = longest
        ? Math.floor(contentWidth / perBarWidth)
        : barNum
      const dataZoom = [
        {
          type: 'slider',
          show: maxBarNum < barNum,
          height: 14,
          right: 5,
          bottom: 0,
          startValue: 0,
          endValue: maxBarNum - 1
        }
      ]
      defaultOption.dataZoom = dataZoom
    },
    setEvent() {
      if (!this.chart || !this.canClick) {
        return
      }
      this.chart.off('click', this.handlerChartClick)
      this.$nextTick(() => {
        this.chart.getZr().on('click', this.handlerChartClick)
      })
    },
    handlerChartClick(params) {
      let seriesIndex = null
      if (params.target && params.target !== undefined) {
        seriesIndex = params.target.seriesIndex
      }

      let pointInPixel = [params.offsetX, params.offsetY]
      let pointInGrid = this.chart.convertFromPixel({ seriesIndex: 0 }, pointInPixel)
      // 柱状图-竖向(数据的索引值)
      let dataIndex = Math.abs(pointInGrid[0])

      this.$emit('click', {dataIndex, seriesIndex})
    }
  },
  beforeMount() {
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    this.chart.off('click', this.handlerChartClick)
    window.removeEventListener('resize', this.handleResize)
  }
}
</script>
<style scoped>
.chart-content {
  background: #ffffff;
  padding: 20px;
  margin-bottom: 20px;
  border-radius: 5px;
  position: relative;
}
.no-data {
  position: absolute;
  left: 0;
  top: 50%;
  width: 100%;
  -webkit-transform: translateY(-50%);
  transform: translateY(-50%);
  text-align: center;
  color: #cccccc;
}
.chart {
  height: 270px;
  width: 100%;
}
.table-title {
  font-weight: 400;
  font-size: 16px;
  color: #333333;
  font-style: normal;
  letter-spacing: 0px;
  line-height: 20px;
  margin-top: 0px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>